//
//  RegisterCenter.swift
//  App_Login
//
//  Created by 蒋晨成 on 2022/1/5.
//

import Center
import Center_Storage
import Foundation
import Service
import Storage

struct MobileStorage: PrimitiveStorable {
    typealias Value = String
    let value: Value
    static let key: String = "mobile"

    init(value: Value) { self.value = value }
}

struct ExpireInStorage: PrimitiveStorable {
    typealias Value = Date
    let value: Value
    static let key: String = "expireIn"

    init(value: Value) { self.value = value }
}

public enum RegisterCenter {}

extension RegisterCenter: TypeName {}

private extension RegisterCenter {
    static let store = StorageCenter.azir[typeName]
}

extension RegisterCenter {
    static var mobile: String? = {
        do {
            guard let mobileStorage: MobileStorage = try store.sync.get() else { return nil }
            return mobileStorage.value
        } catch {
            logger.error("\(error)")
            return nil
        }
    }() {
        didSet {
            do {
                switch mobile {
                case .none:
                    try store.sync.delete(key: MobileStorage.key)
                case .some(let mobile):
                    try store.sync.put(storableObject: MobileStorage(value: mobile))
                }
            } catch {
                logger.error("\(error)")
            }
        }
    }

    static var expireIn: Date? = {
        do {
            guard let expireInStorage: ExpireInStorage = try store.sync.get() else { return nil }
            return expireInStorage.value
        } catch {
            logger.error("\(error)")
            return nil
        }
    }() {
        didSet {
            do {
                switch expireIn {
                case .none:
                    try store.sync.delete(key: ExpireInStorage.key)
                case .some(let expireIn):
                    try store.sync.put(storableObject: ExpireInStorage(value: expireIn))
                }
            } catch {
                logger.error("\(error)")
            }
        }
    }
}
